﻿using System;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;


namespace Ini
{
    public class IniFile
    {
        public string path;

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        [DllImport("kernel32.dll")]
        private static extern int GetPrivateProfileSection(string lpAppName, byte[] lpszReturnBuffer, int nSize, string lpFileName);


        public IniFile()
        {
            path = "C:\\Sapiens\\";

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            path += System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + "\\";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            path += System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".ini";

        }

        public IniFile(string sFilename)
        {
            path = sFilename;

        }


        public void IniWriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, this.path);
        }

        public string IniReadValue(string Section, string Key)
        {
            StringBuilder temp = new StringBuilder(5000);
            int i = GetPrivateProfileString(Section, Key, "", temp, 5000, this.path);
            return temp.ToString();

        }

        public String[] ReadSection(string sSection)
        {
            byte[] buffer = new byte[2048];
            GetPrivateProfileSection(sSection, buffer, 2048, path);
            String[] tmp = Encoding.ASCII.GetString(buffer).Trim('\0').Split('\0');
            return tmp;
        }

        public string IniReadValue(string Section, string Key, string sDefault)
        {
            string sRet = IniReadValue(Section, Key);
            if (sRet.Length == 0)
            {
                sRet = sDefault;
                IniWriteValue(Section, Key, sRet);
            }
            return sRet;
        }
    }
}
